package com.meibao.page.service;

import com.meibao.item.pojo.*;
import com.meibao.page.client.BrandClient;
import com.meibao.page.client.CategoryClient;
import com.meibao.page.client.GoodsClient;
import com.meibao.page.client.SpecificationClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
@Service
public class PageService {
    @Autowired
    private BrandClient brandClient;
    @Autowired
    private CategoryClient categoryClient;
    @Autowired
    private GoodsClient goodsClient;
    @Autowired
    private SpecificationClient specClient;
    @Autowired
    private TemplateEngine templateEngine;

    public Map<String, Object> loadModelData(Long spuId) {
        Map<String, Object> model = new HashMap<>();
        // 查询spu
        Spu spu = goodsClient.querySpuById(spuId);
        // 查询spuDetail
        SpuDetail detail = goodsClient.queryDetailById(spuId);
        // 查询sku
        List<Sku> skus = this.goodsClient.querySkuBySpuId(spuId);
        // 准备品牌数据
        Brand brand = brandClient.queryBrandById(spu.getBrandId());
        // 准备商品分类
        List<Category> categories = categoryClient.queryCategoryByIds(
                Arrays.asList(spu.getCid1(),spu.getCid2(),spu.getCid3()));
        // 查询规格组及组内参数
        List<SpecGroup> specs = specClient.queryAllByCid(spu.getCid3());

        // 装填模型数据
        model.put("spu",spu);
        model.put("title",spu.getTitle());
        model.put("sub_title",spu.getSubTitle());
        model.put("skus",skus);
        model.put("detail",detail);
        model.put("brand",brand);
        model.put("categories",categories);
        model.put("specs",specs);

        return model;
    }

    public void createHtml(Long spuId){
        //上下文
        Context context = new Context();
        context.setVariables(loadModelData(spuId));
        //输出流
        File dest = new File("f://test//", spuId + ".html");

        if(dest.exists()){
            dest.delete();
        }

        try(PrintWriter writer = new PrintWriter(dest,"UTF-8")){
            //生成HTML
            templateEngine.process("item", context, writer);
        }catch (Exception e){
            log.error("【静态页服务】 生成静态页异常",e);
        }

    }

    public void deleteHtml(Long spuId) {
        File dest = new File("f://test//", spuId + ".html");
        if(dest.exists()){
            dest.delete();
        }
    }
}
